import util from '../../../../utils/utils';
import bmap from '../../../../utils/bmap-wx.min';
import Dialog from "../../../../dist/dialog/dialog";

let wxMarkerData = [];
let sysInfo = wx.getSystemInfoSync();
let height = sysInfo.windowHeight;
let areaHeight = height - util.rpxToPx(500);

Page({
  /**
   * 页面的初始数据
   */
  map: null,
  BMap: null,
  isHide: false,
  data: {
    //百度地图用
    markItem: [],
    markers: [],
    latitude: '',
    longitude: '',
    //======
    value: '',
    openArea: false,
    pass: false,
    addr_id: 0,
    modify: false,
    areaHeight: areaHeight,
    gps: {
      longitude: 0,
      latitude: 0,
    },
  },
  /**
   * 页面载入完成
   */
  initPage: function (options) {
    let self = this;
    let _data;
    if (options.detail) {
      _data = JSON.parse(options.detail);
    }
    let sysInfo = wx.getSystemInfoSync();
    let height = sysInfo.windowHeight;
    let areaHeight = height - util.rpxToPx(500);
    self.setData({
      areaHeight: areaHeight
    });
    self.initMap();
  },
  onShow: function () {
    if (this.isHide === true) {
      this.initMap();
    }
  },
  initMap: function () {
    let self = this;
    // 新建百度地图对象
    self.BMap = new bmap.BMapWX({
      ak: util.BdKey
    });
    this.map = wx.createMapContext('map');
    // // 发起regeocoding检索请求
    this.searchByBd();
  },
  searchByBd: function (gps) {
    let self = this;
    let location = false;
    if (gps) {
      location = gps.latitude + ',' + gps.longitude;
    }
    this.BMap.regeocoding({
      location: location,
      fail: function (result) {
        if (result.errMsg === 'getLocation:fail auth deny') {
          Dialog.confirm({
            title: '温馨提示',
            message: '您拒绝授权位置信息，我们无法为您提供地址选择！',
            confirmButtonText: "去开启",
            confirmButtonOpenType: "openSetting",
            cancelButtonText: "狠心拒绝"
          }).then(() => {
            self.isHide = true;
          }).catch(() => {
            util.msg('无法选择地址！');
          });
        }
      },
      success: function (data) {
        wxMarkerData = [];
        let result = data.originalData.result;
        let item = {};
        let basicInfo = result.addressComponent;
        for (let i = 0; i < result.pois.length; i++) {
          item = result.pois[i];
          wxMarkerData[i] = {
            id: item['uid'],
            longitude: item['point']['x'],
            latitude: item['point']['y'],
            title: item["name"],
            address: item["addr"],
            area: basicInfo["district"],
            city: basicInfo["city"],
            province: basicInfo["province"],
          };
        }
        self.setData({
          markItem: [],
          markers: wxMarkerData
        });
        if (wxMarkerData.length > 0) {
          self.setData({
            latitude: result['location'].lat,
            longitude: result['location'].lng
          });
        }
      },
      iconPath: '/images/icon/mark_red.png',
      iconTapPath: '/images/icon/mark_red.png'
    });
  },
  toCenter: function () {
    this.map.moveToLocation();
  },
  showmapinfo: function (e) {
    let self = this;
    if (e.type === 'end' && e.causedBy === 'drag') {
      this.map.getCenterLocation({
        success(res) {
          self.searchByBd({
            latitude: res.latitude,
            longitude: res.longitude
          })
        }
      });
    }
  },
  changeMarkerColor: function (data, i) {
    let that = this;
    let markers = [];
    for (var j = 0; j < data.length; j++) {
      if (j === i) {
        // 此处需要在相应路径放置图片文件
        data[j].iconPath = "/images/icon/mark_red.png";
      } else {
        // 此处需要在相应路径放置图片文件
        data[j].iconPath = "/images/icon/mark_red.png";
      }
      markers[j](data[j]);
    }
    that.setData({
      markers: markers
    });
  },
  selectArea: function (e) {
    let item = e.currentTarget.dataset.item;
    let pages, prevPage;
    let app = getApp();
    if (item) {
      pages = getCurrentPages();
      if (pages.length > 1) {
        prevPage = pages[pages.length - 2];
        if (prevPage.route === 'pages/me/address/new/new') {
          prevPage.upAreaInfo(item);
        }
        app.globalData.tempParam = item;
        setTimeout(function () {
          wx.navigateBack();
        }, 100);
      }
    } else {
      util.msg('没有选择正确的地址');
    }
  },
  onChange(e) {
    this.setData({
      value: e.detail
    });
  },
  onClear: function () {
    this.setData({
      value: ''
    });
    this.searchByBd();
  },
  onSearch: function (event) {
    let self = this;
    let location = this.data.latitude + ',' + this.data.longitude;
    if (this.data.value === '') {
      this.searchByBd();
      return false;

    }
    this.setData({
      keyword: this.data.value
    });
    this.BMap.search({
      query: this.data.value,
      location: location,
      radius: 50000,
      scope: 2,
      fail: function (result) {
        console.log(result);
      },
      success: function (data) {
        wxMarkerData = [];
        let result = data.originalData.results;
        let item = {};
        for (let i = 0; i < result.length; i++) {
          item = result[i];
          wxMarkerData[i] = {
            id: i,
            longitude: item['location']['lng'],
            latitude: item['location']['lat'],
            title: item["name"],
            address: item["address"],
            area: item["area"],
            city: item["city"],
            province: item["province"],
          };
        }
        if (wxMarkerData.length > 0) {
          self.setData({
            markItem: [{
              id: 1,
              title: 'test',
              width: '56rpx',
              height: '74rpx',
              iconPath: '/images/icon/mark_red.png',
              latitude: wxMarkerData[0].latitude,
              longitude: wxMarkerData[0].longitude,
            }],
            markers: wxMarkerData,
            latitude: wxMarkerData[0].latitude,
            longitude: wxMarkerData[0].longitude
          });
        } else {
          self.setData({
            markers: wxMarkerData,
          });
        }
      },
      iconPath: '/images/icon/mark_red.png',
      iconTapPath: '/images/icon/mark_red.png'
    });
  },
});
